import { fetchResources } from './utils'

export const importHTML = async url => {
  const template = document.createElement('div')
  const html = await fetchResources(url)
  template.innerHTML = html
  window.template = template
  // 获取所有文档中的script节点
  const scripts = template.querySelectorAll('script')
  console.log(scripts, 'scripts=========')

  // 获取所有script标签中的代码[代码,代码,代码]
  function getExternalScripts () {
    return Promise.all(
      Array.from(scripts).map(script => {
        const src = script.getAttribute('src')
        if (!src) {
          // 内嵌的代码类型script
          return Promise.resolve(script.innerHTML)
        } else {
          // 外链的script  需要单独处理下 如果没有域名的src则需要拼接entry
          return fetchResources(src.startsWith('http') ? src : `${url}${src.includes('/subapp/sub-react') ? src.replace('/subapp/sub-react', '') : src}`)
        }
      })
    )
  }
  function evil (fn) {
    var Fn = Function
    return new Fn('return ' + fn)
  }

  // 获取并执行所有的script脚本代码
  async function execScripts () {
    const scrips = await getExternalScripts()

    // 手动构造一个 CommonJS 模块环境 用于获取子应用的名称、路由等信息
    const module = { exports: {} }
    const exports = module.exports
    scrips.forEach(code => {
      evil(code)()
    })
    // const as = window['sub-vue-app']
    // as.mount && as.mount()

    console.log(module.exports, 'module.exports=========', exports, window)
    return window['sub-vue-app'] || module.exports
  }
  return {
    template,
    getExternalScripts,
    execScripts
  }
}
